package com.bmic.cotacoes;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import android.util.Log;

public class Parser {

	
	private URL feedUrl;
	private InputStream xml;

	
	public Parser() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Papel recuperaInformacoes(String nomePapel)
			throws ParserConfigurationException, SAXException, IOException {
		
		this.feedUrl = new URL("http://www.bmfbovespa.com.br/Pregao-Online/ExecutaAcaoAjax.asp?CodigoPapel="+nomePapel);		
		Log.i("Cotacoes", feedUrl.getPath());
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		DocumentBuilder db = dbf.newDocumentBuilder();

		xml = getInputStream();
		Document doc = db.parse(xml);
		removeWhitespaceNodes(doc.getDocumentElement());
		Papel p = new Papel();
		p.setCodigo(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Codigo").getNodeValue());
		p.setNome(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Nome").getNodeValue());
		p.setData(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Data").getNodeValue());
		p.setAbertura(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Abertura").getNodeValue());
		p.setMinimo(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Minimo").getNodeValue());
		p.setMaximo(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Maximo").getNodeValue());
		p.setMedio(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Medio").getNodeValue());
		p.setUltimo(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Ultimo").getNodeValue());
		p.setOscilacao(doc.getDocumentElement().getFirstChild().getAttributes()
				.getNamedItem("Oscilacao").getNodeValue());

		return p;
	}

	public InputStream getInputStream() {
		try {
			return feedUrl.openConnection().getInputStream();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static void removeWhitespaceNodes(Element e) {
		NodeList children = e.getChildNodes();
		for (int i = children.getLength() - 1; i >= 0; i--) {
			Node child = children.item(i);
			if (child instanceof Text
					&& ((Text) child).getData().trim().length() == 0) {
				e.removeChild(child);
			} else if (child instanceof Element) {
				removeWhitespaceNodes((Element) child);
			}
		}
	}
}
